﻿using System;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.Abstractions;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ActionResults;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ModelBinders;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ValueProviders;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax.Controllers
{
    public abstract class ControllerBase
    {
        protected ControllerBase()
        {
            ActionInvoker = new ControllerActionInvoker();
        }

        public void Execute(RequestContext context)
        {
            Initialize(context);
            if (!ActionInvoker.InvokeControllerAction(Context, Context.RequestContext.ActionName))
                HandleUnknownAction(Context.RequestContext.ActionName);
        }

        protected ActionResult Json(Object data)
        {
            return new JsonResult(data);
        }

        protected ActionResult Content(String content)
        {
            return new ContentResult(content);
        }

        private void Initialize(RequestContext context)
        {
            Context = new ControllerContext(context, this);
        }

        private void HandleUnknownAction(string actionName)
        {
            // todo: throw custom exception
            throw new Exception("Action doesn't exist");
        }

        public ControllerContext Context { get; private set; }

        public ControllerActionInvoker ActionInvoker { get; set; }

        public virtual ValueProviderFactoryCollection ValueProviders { get; set; }

        public virtual ModelBinderDictionary ModelBinders { get; set; }


    }
}